package com.lyp.lease.web.admin.custom.converter;

import com.lyp.lease.model.enums.BaseEnum;
import com.lyp.lease.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 *
 * 功能是String转某个枚举类
 * 根据不同的枚举类构造不同功能的Converter
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    /**
     * getConverter 获取Converter转换器
     * @param targetTypeEnum 枚举类的字节码对象
     * @return 返回一个Converter
     * <T extends BaseEnum> 一定是继承了BaseEnum的枚举类，比如ItemType枚举类
     */
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetTypeEnum) {
        return (String code)->{
            for (T enumConstant : targetTypeEnum.getEnumConstants()) {
                if (enumConstant.getCode().equals(Integer.parseInt(code))){
                    return enumConstant;
                }
            }
            throw new IllegalArgumentException("参数错误");
        };
    }
}
